package by.grsu.shakh.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.shakh.entity.Catalog;
import by.grsu.shakh.table.CatalogTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class CatalogDao extends AbstractDao<CatalogTable, Catalog> {
	public CatalogDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	public Catalog searchByName(String desiredCatalog) {
		final CatalogTable catalogTable = deserializeFromXml();
		Catalog catalog = new Catalog();
		for (final Catalog c : catalogTable.getRows()) {
			if (c.getName().equals(desiredCatalog)) {
				catalog = c;
				break;
			}
		}
		return catalog;
	}

	@Override
	public void saveNew(final Catalog newCatalog) {
		newCatalog.setId(getNextId());
		final CatalogTable catalogTable = deserializeFromXml();
		catalogTable.getRows().add(newCatalog);
		serializeToXml(catalogTable);
	}

	@Override
	public void update(final Catalog entity) {
		final CatalogTable catalogTable = deserializeFromXml();
		for (final Catalog c : catalogTable.getRows()) {
			if (c.getId().equals(entity.getId())) {
				c.setName(entity.getName());
				break;
			}
		}
		serializeToXml(catalogTable);

	}

	@Override
	public Catalog get(Serializable id) {
		final CatalogTable catalogTable = deserializeFromXml();
		for (final Catalog c : catalogTable.getRows()) {
			if (c.getId().equals(id)) {
				return c;
			}
		}

		return null;
	}

	@Override
	public List<Catalog> getAll() {
		final CatalogTable catalogTable = deserializeFromXml();
		return catalogTable.getRows();
	}
	public List<Long> getAllID() {
		final CatalogTable catalogTable = deserializeFromXml();
		List<Long> listID= new ArrayList();
		for (Catalog c : catalogTable.getRows()) {
			listID.add(c.getId());
		}
		return listID;
	}


	@Override
	public void delete(Serializable id) {
		final CatalogTable catalogTable = deserializeFromXml();
		Catalog toBeDeletedCatalog = null;
		for (final Catalog c : catalogTable.getRows()) {
			if (c.getId().equals(id)) {
				toBeDeletedCatalog = c;
				break;
			}
		}
		catalogTable.getRows().remove(toBeDeletedCatalog);
		serializeToXml(catalogTable);
	}

	@Override
	protected Class<CatalogTable> getTableClass() {
		return CatalogTable.class;
	}
}
